package com.yzr.common.page;

import java.util.Collections;
import java.util.List;

/**
 * @description 集合分页工具类
 * @author: yx-0173
 * @date: 2021-05-11 12:45
 **/
public class PageUtil {
    /**
     * 常量1
     */
    public static final Integer NUM_ONE = 1;
    /**
     * 常量0
     */
    public static final Integer NUM_ZERO = 0;
    /**
     * 常量10
     */
    public static final Integer TEN = 10;

    /**
     * @param list     集合
     * @param pageNum  分页当前页
     * @param pageSize 分页页总数
     * @return List<T>
     */
    public static <T> List<T> startPage(List<T> list, Integer pageNum, Integer pageSize) {
        if (list == null || list.size() <= NUM_ZERO) {
            return list;
        }
        pageNum = pageNum.equals(NUM_ZERO) ? NUM_ONE : pageNum;
        pageSize = pageSize.equals(NUM_ZERO) ? TEN : pageSize;
        // 记录总数
        int count = list.size();
        int fromIndex = (pageNum - NUM_ONE) * pageSize;
        if (fromIndex >= count || fromIndex < 0) {
            // 空数组
            return Collections.emptyList();
        }
        int toIndex = pageNum * pageSize;
        if (toIndex >= count) {
            toIndex = count;
        }
        return list.subList(fromIndex, toIndex);
    }
}
